package com.scut.dispatching_server.service;

import com.scut.dispatching_server.config.GlobalVariables;
import com.scut.dispatching_server.model.Supplier;
import com.scut.dispatching_server.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class SupplierCache {
    @Autowired
    private RedisUtil redisUtil;

    public boolean saveToCache(Supplier supplier) {
        Map<String, Object> supplierMap = new HashMap<>();
        supplierMap.put("lon", supplier.getLon());
        supplierMap.put("lat", supplier.getLat());
        supplierMap.put("time", supplier.getTime());
        redisUtil.hmset(supplier.getId(), supplierMap, GlobalVariables.REAL_TIME_LENGTH);
        return true;
    }

    public ArrayList<String> getCachedSuppliers() {
        ArrayList<String> supplierIds = new ArrayList<>();
        Set<Object> suppliersSet = redisUtil.sGet(GlobalVariables.ALIVE_SUPPLIER_SET_KEY);
        for (Object supplierId : suppliersSet) {
            supplierIds.add((String)supplierId);
        }
        return supplierIds;
    }

    public long addAliveSupplier(String id) {
        return redisUtil.sSet(GlobalVariables.ALIVE_SUPPLIER_SET_KEY, id);
    }

    public Map<Object, Object> getSupplier(String key) {
        return redisUtil.hmget(key);
    }

    public boolean deleteSupplier(String id) {
        if (redisUtil.setRemove(GlobalVariables.ALIVE_SUPPLIER_SET_KEY, id) > 0) {
            return true;
        }
        return false;
    }
}
